import moment          from 'moment';
import Storage         from './storage';
import API             from '../api/api';
import { authRequest } from "../api/request";

const { MIX_TOKEN_NAME, MIX_TOKEN_EXPIRED_AT } = process.env;

export const setAuthToken = (data) => {
    Storage.setItem(MIX_TOKEN_NAME, data.access_token);
    Storage.setItem(MIX_TOKEN_EXPIRED_AT, new Date().getTime() + (data.expires_in * 1000));
};

export const clearAuth = () => {
    Storage.removeItem(MIX_TOKEN_NAME);
    Storage.removeItem(MIX_TOKEN_EXPIRED_AT);

};

export const mergeApi = (api, obj = {}) => {
    let data = API[ api ];
    if (!data) {
        throw 'API NOT EXISTS';
    }
    return Object.assign({}, data, obj);
}

export const getAuthToken = () => {
    let token = Storage.getItem(MIX_TOKEN_NAME);
    let at    = Storage.getItem(MIX_TOKEN_EXPIRED_AT);

    if (!token || !at) {
        return false;
    }

    return {
        token,
        at,
    }
};

export const apiRequest = async (name, data = {}, url = '', back = false) => {
    const op = mergeApi(name, data);
    if (url) {
        op.url += url;
    }

    return await authRequest(op, back);
}
